package biznussoft.fieldservice360;
             
import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import biznussoft.fieldservice360.service.UnCaughtException;
import biznussoft.fieldservice360.utils.Session;

import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.ui.sfnative.SalesforceActivity;

public class HomeActivity extends SalesforceActivity {

    public RestClient client;
    private RelativeLayout rLayout;
    private ImageView mInventory,mServiceOrder;
    public static HomeActivity mActivity;
    private String id;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.homepage);                           
		Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this));
		rLayout = (RelativeLayout) findViewById(R.id.rrlayout);
		mInventory = (ImageView) findViewById(R.id.inventory);
		mServiceOrder = (ImageView) findViewById(R.id.serviceOrder);
		mActivity = this;
	}             
	
	
	@Override 
	public void onResume() {
		rLayout.setVisibility(View.INVISIBLE);
		super.onResume();
	}		
	
	@Override
	public void onResume(RestClient client) {
		this.client = client;
		mActivity.client = client;
		Session.sAccesToken = client.getAuthToken();
		Session.sInstanceUrl = client.getClientInfo().instanceUrl.toString();
		String query = "select id from FConnect__Group_Members__c where user__c="
				+ "'" + client.getClientInfo().userId + "'";
		try {
			
			 sendRequest(query);
				

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		rLayout.setVisibility(View.VISIBLE);
	}

	public void accountAction(View v) {
		startActivity(new Intent(this, AccountsActivity.class));
	}
	public void myActivities(View v) {
		startActivity(new Intent(this, MyActivities.class));
	}
	public void inventoryAction(View v) {
		startActivity(new Intent(this, InventoryActivity.class));
	}
	
	public void contactAction(View v){
		startActivity(new Intent(this,ContactsActivity.class));
	}
	
	public void serviceAction(View v){
		startActivity(new Intent(this,ServiceOrderActivity.class));
	}
	
	public void logoutAction(View v){
		SalesforceSDKManager.getInstance().logout(this);
	}
	
	private void sendRequest(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);

		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {   
					
					Log.i("NCS","GroupMember is  :"+result);
					String query = "select  FirstName, LastName from User where Id="+"'"+client.getClientInfo().userId+"'";
					getOwnerName(query);
					JSONObject jsonObject1 = new JSONObject(result.asString());
					JSONArray jsonArray = jsonObject1.getJSONArray("records");
					Log.i("NCS","jsonArray length  :"+jsonArray.getJSONObject(0).getString("Id"));
					Session.sID = jsonArray.getJSONObject(0).getString("Id");
					
					
				} catch (Exception e) {                      
					onError(e);
					mInventory.setVisibility(View.VISIBLE);
					mServiceOrder.setVisibility(View.VISIBLE);
				}               
			}

			@Override
			public void onError(Exception exception) {
              
			}     
		});
	}
	private void getOwnerName(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);
		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {                                                          
					Log.i("RGT","RestResponse is  :"+result);
					JSONArray records = result.asJSONObject().getJSONArray("records");
					Session.sFirstName = records.getJSONObject(0).getString("FirstName");
					Session.sLastName = records.getJSONObject(0).getString("LastName");
					
				} catch (Exception e) {                  
					onError(e);
				}               
			}

			@Override
			public void onError(Exception exception) {
              
			}
		});
	}
	

	/**
	 * Called when "Logout" button is clicked. 
	 * 
	 * @param v
	 */
	/*public void onLogoutClick(View v) {
		SalesforceSDKManager.getInstance().logout(this);
	}*/
	
	/**
	 * Called when "Clear" button is clicked. 
	 * 
	 * @param v
	 */
	/*public void onClearClick(View v) {
		listAdapter.clear();
	}*/	

	/**           
	 * Called when "Fetch Contacts" button is clicked
	 * 
	 * @param v
	 * @throws UnsupportedEncodingException 
	 */
	/*public void onFetchContactsClick(View v) throws UnsupportedEncodingException {
        sendRequest("SELECT Name FROM Contact");
	}*/

	/**
	 * Called when "Fetch Accounts" button is clicked
	 * 
	 * @param v
	 * @throws UnsupportedEncodingException 
	 */
	/*public void onFetchAccountsClick(View v) throws UnsupportedEncodingException {
		sendRequest("SELECT Name FROM Account");
	}*/	
	
	
}
